<?php
  // Global variables.
  $globalTableName = "factoid";

  // Do not change the following variables
  $sqlwherequery = "";
  $postSearchValue = "";
  $postSearchCriteria = "";
  $postStatusValue = "";
  $postTypeValue = "";
  $postAvailabilityValue = "";
  $postOrderByOrder = "";
  $postOrderByColumn = "";
  $postCurrentPage = "";
  $postExactMatch = "";
  $postAction = "";
  $httpUsername = "";
  $startindex = 0;

  while (list($key,$value) = each($_POST)) {
    if ($key == "search_value") {
      $postSearchValue = $value;
    } else if ($key == "search_criteria") {
      $postSearchCriteria = $value;
    } else if ($key == "status") {
      $postStatusValue = $value;
    } else if ($key == "type") {
      $postTypeValue = $value;
    } else if ($key == "availability") {
      $postAvailabilityValue = $value;
    } else if ($key == "orderby_order") {
      $postOrderByOrder = $value;
    } else if ($key == "orderby_column") {
      $postOrderByColumn = $value;
    } else if ($key == "currentpage") {
      $postCurrentPage = $value;
    } else if ($key == "match_type") {
      $postExactMatch = $value;
    } else if ($key == "action") {
      $postAction = $value;
    }
  }

  $postID = "";
  $postAction = "";
  $postFactoidValue = "";

  foreach($_POST as $key => $value) {
    if ($key == "id") {
      $postID = $value;
    } else if ($key == "action") {
      $postAction = $value;
    } else if ($key == "factoidValue") {
      $postFactoidValue = $value;
    }
  }

  if ($postCurrentPage != "") {
    $startindex = 50 * (intval($postCurrentPage) - 1);
  }

  function print_filtering_section($postAction, $postStatusValue, $postTypeValue, $postSearchCriteria, $postSearchValue, $postExactMatch) {
    print "    <table border='0' cellpadding='0' cellspacing='0' width='1024' class='content_header'>\n" .
          "      <tr>\n" .
          "        <td width='100' align='left' class='header_title'>FILTER ON:</td>\n" .
          "        <td width='67' align='right' class='header_title'>Status:&nbsp;</td>\n" .
          "        <td width='145' align='left'>\n" .
          "          <select name='status' id='status' onchange=\"getItem('currentpage').value='1';\" class='form_element'>\n";
    // Dynamically populate this element, and set the selected item to the previous value
    if ($postStatusValue == "all" || ($postStatusValue == "" && $postAction == "search")) {
      print "            <option value='all' selected>All Factoids</option>\n";
    } else {
      print "            <option value='all'>All Factoids</option>\n";
    }

    if ($postStatusValue == "active") {
      print "            <option value='active' selected>Active Factoids</option>\n";
    } else {
      print "            <option value='active'>Active Factoids</option>\n";
    }

    if ($postStatusValue == "deleted") {
      print "            <option value='deleted' selected>Deleted Factoids</option>\n";
    } else {
      print "            <option value='deleted'>Deleted Factoids</option>\n";
    }

    print "          </select>\n" .
          "        </td>\n" .
          "        <td width='67' align='right' class='header_title'>Type:&nbsp;</td>\n" .
          "        <td width='100' align='left'>\n" .
          "          <select name='type' id='type' onchange=\"getItem('currentpage').value='1';\" class='form_element'>\n";

    // Dynamically populate this element, and set the selected item to the previous value
    if ($postTypeValue == "all" || ($postTypeValue == "" && $postAction == "search")) {
      print "            <option value='all' selected>All Types</option>\n";
    } else {
      print "            <option value='all'>All Types</option>\n";
    }

    if ($postTypeValue == "F") {
      print "            <option value='F' selected>Factoids</option>\n";
    } else {
      print "            <option value='F'>Factoids</option>\n";
    }

    if ($postTypeValue == "T") {
      print "            <option value='T' selected>Triggers</option>\n";
    } else {
      print "            <option value='T'>Triggers</option>\n";
    }

    if ($postTypeValue == "O") {
      print "            <option value='O' selected>Other</option>\n";
    } else {
      print "            <option value='O'>Other</option>\n";
    }

    print "          </select>\n" .
          "        </td>\n" .
          "        <td width='46' align='right' class='header_title'>And&nbsp;</td>\n" .
          "        <td width='150' align='left'>\n" .
          "          <select name='search_criteria' id='search_criteria' onchange=\"getItem('currentpage').value='1';\" class='form_element'>\n";

    // Dynamically populate this element, and set the selected item to the previous value
    if ($postTypeValue == "both" || ($postTypeValue == "" && $postAction == "search")) {
      print "            <option value='both' selected>Key or Value</option>\n";
    } else {
      print "            <option value='both'>Key or Value</option>\n";
    }

    if ($postSearchCriteria == "key") {
      print "            <option value='key' selected>Key</option>\n";
    } else {
      print "            <option value='key'>Key</option>\n";
    }

    // Too slow
    if ($postSearchCriteria == "value") {
      print "            <option value='value' selected>Trigger Value</option>\n";
    } else {
      print "            <option value='value'>Trigger Value</option>\n";
    }

    printf("          </select>&nbsp; is:\n" .
           "        </td>\n" .
           "        <td width='162' align='center'><input type='text' name='search_value' id='search_value' maxlength='50' size='12' value='%s' " .
           "onchange=\"getItem('currentpage').value='1';getItem('action').value='search';\" class='form_element'></td>\n",
           $postSearchValue);

    if ($postExactMatch == "on") {
      printf("        <td width='137' align='left'>Exact Match<input type='checkbox' name='match_type' id='match_type' class='form_element' checked></td>\n");
    } else {
      printf("        <td width='137' align='left'>Exact Match<input type='checkbox' name='match_type' id='match_type' class='form_element'></td>\n");
    }

    print "        <td width='50' align='center'><div id='go_button' class='middle_nav_button' " .
          "onmouseover=\"changeClass('go_button','middle_nav_button_hover');\" " .
          "onmouseout=\"changeClass('go_button','middle_nav_button');\" " .
          "onclick=\"getItem('currentpage').value='1';getItem('action').value='search';document.factoids.submit();\">Go</div></td>\n" .
          "      </tr>\n" .
          "    </table>\n";
  }

  function print_navigation_section($globalTableName, $sqlwherequery, $postCurrentPage) {
    $sqlselectquery2 = "SELECT COUNT(`factoid_id`) AS `factoid_id` FROM `" . $globalTableName . "` `fact` ";
    $sqlquery2 = $sqlselectquery2 . $sqlwherequery;
    $queryresult = mysql_query($sqlquery2);
    $row = mysql_fetch_array($queryresult);
    $totalnoofresults = intval($row["factoid_id"]);
    $numberofpages = ceil($totalnoofresults/50);

    print "    <table border='0' cellpadding='0' cellspacing='0' width='1024' class='content_header'>\n" .
          "      <tr>\n" .
          "        <td width='120' align='left' class='header_title'>NAVIGATION</td>\n";

    // Build and display the navigation section
    if ($numberofpages == 0) {
      printf("        <td width='130' align='center' class='header_title'>%d Pages</td>\n",
             $numberofpages);
    } else if ($numberofpages == 1) {
      printf("        <td width='130' align='center' class='header_title'>%d Page:&nbsp;&nbsp;</td>\n",
             $numberofpages);
    } else {
      printf("        <td width='130' align='center' class='header_title'>%d Pages:&nbsp;&nbsp;</td>\n",
             $numberofpages);
    }

    print "        <td width='1165' align='center' class='header_title'>\n";

    // Get the requested page right. I'll impact the rest of the routine
    if ($postCurrentPage != "") {
      $postCurrentPage = intval($postCurrentPage);
    } else {
      $postCurrentPage = 1;
    }

    // Only enable going back if there was more than one page, and the user was not on the first page already
    if ($numberofpages > 1 && $postCurrentPage > 1) {
      printf("          <div id='first_button' class='first_nav_button' " .
             "onmouseover=\"changeClass('first_button','first_nav_button_hover');\" " .
             "onmouseout=\"changeClass('first_button','first_nav_button');\" " .
             "onclick=\"gotopage(-1,%d);\" " .
             ">&lt;&lt;&nbsp;Previous</div>\n",
             $numberofpages);
    } else if ($numberofpages > 1) {
      printf("          <div id='first_button' class='first_nav_button' " .
             "onmouseover=\"changeClass('first_button','first_nav_button_hover');\" " .
             "onmouseout=\"changeClass('first_button','first_nav_button');\" " .
             ">&lt;&lt;&nbsp;Previous</div>\n",
             $numberofpages);
    }

    if ($numberofpages <= 14) {
      // No ... is required
      $currentpage = 1;

      while($currentpage <= $numberofpages) {
        if ($postCurrentPage == $currentpage) {
          printf("          <div id='button%d' class='middle_nav_button_selected' " .
                 "onmouseover=\"changeClass('button%d','middle_nav_button_hover');\" " .
                 ">%d</div>\n",
                 $currentpage, $currentpage, $currentpage);
        } else {
          printf("          <div id='button%d' class='middle_nav_button' " .
                 "onmouseover=\"changeClass('button%d','middle_nav_button_hover');\" " .
                 "onmouseout=\"changeClass('button%d','middle_nav_button');\" " .
                 "onclick=\"getItem('currentpage').value='%d';document.factoids.submit();\" " .
                 ">%d</div>\n",
                 $currentpage, $currentpage, $currentpage, $currentpage, $currentpage);
        }

        $currentpage = $currentpage + 1;
      }
    } else if ($numberofpages > 0) {
      // Preserve the posted (requested) page.
      // This variable will be iterated on, and its original value lost
      $currentpage = $postCurrentPage;

      if ($currentpage == 1) {
        // Add 11 items, for a total of 52 visible items. There will be a ...  before the last page shortcut
        $pageoffset = 51;
      } else if ($currentpage == 2) {
        // Add 50 items, for a total of 51 visible items. There will be a ...  before the last page shortcut
        // Since the '1' will also be present, it needs one more item
        $pageoffset = 50;
      } else if ($currentpage > 2 && ($currentpage + 11) >= $numberofpages) {
        $pageoffset = 51;
      } else if ($currentpage > 2) {
        // Add 9 items between the ... delimiter (first and last)
        $pageoffset = 49;
      }

      // Add the shortcut to the first page (clickable)
      if ($currentpage > 1) {
        print "          <div id='button0' class='middle_nav_button' " .
              "onmouseover=\"changeClass('button0','middle_nav_button_hover');\" " .
              "onmouseout=\"changeClass('button0','middle_nav_button');\" " .
              "onclick=\"getItem('currentpage').value='1';document.factoids.submit();\" " .
              ">1</div>\n";
      }

      // Add a delimiter (...) after the first page
      if ($currentpage > 2) {
        print "          <div id='button0_2' class='middle_nav_button' " .
              "onmouseover=\"changeClass('button0_2','middle_nav_button_hover');\" " .
              "onmouseout=\"changeClass('button0_2','middle_nav_button');\" " .
              ">...</div>\n";
      }

      // This will determine the upper limit of the next loop
      if ($currentpage + $pageoffset > $numberofpages) {
        $maxpage = $numberofpages;
      } else {
        $maxpage = $currentpage + $pageoffset;
      }

      // In order to keep the number of items on the screen uniform, especially once you reach the end,
      // start the loop a little earlier (11 items before the last page, to be exact)
      if ($maxpage - $currentpage < 10 && $pageoffset == 11) {
        $currentpage = $maxpage - 11;
      }

      while($currentpage <= $maxpage) {
        if ($currentpage == $postCurrentPage) {
          // place the current page, highlighted
          printf("          <div id='button%d' class='middle_nav_button_selected'>%d</div>\n",
            $currentpage, $currentpage);
        } else {
          printf("          <div id='button%d' class='middle_nav_button' " .
                 "onmouseover=\"changeClass('button%d','middle_nav_button_hover');\" " .
                 "onmouseout=\"changeClass('button%d','middle_nav_button');\" " .
                 "onclick=\"getItem('currentpage').value='%d';document.factoids.submit();\" " .
                 ">%d</div>\n",
                 $currentpage, $currentpage, $currentpage, $currentpage, $currentpage);
        }

        $currentpage = $currentpage + 1;
      }

      if ($currentpage < ($numberofpages - 1)) {
        // We haven't reached the end yet
        // Place a '...' and a shortcut to the last page
        printf("          <div id='button%d' class='middle_nav_button' " .
               "onmouseover=\"changeClass('button%d','middle_nav_button_hover');\" " .
               "onmouseout=\"changeClass('button%d','middle_nav_button');\" " .
               ">...</div>\n",
               $numberofpages + 1, $numberofpages + 1, $numberofpages + 1);
        printf("          <div id='button%d' class='middle_nav_button' " .
               "onmouseover=\"changeClass('button%d','middle_nav_button_hover');\" " .
               "onmouseout=\"changeClass('button%d','middle_nav_button');\" " .
               "onclick=\"getItem('currentpage').value='%d';document.factoids.submit();\" " .
               ">%d</div>\n",
               $numberofpages + 2, $numberofpages + 2, $numberofpages + 2, $numberofpages, $numberofpages);
      }
    }

    if ($numberofpages > 1 && $postCurrentPage != $numberofpages) {
      // A functional 'next' button is required
      printf("          <div id='last_nav_button' class='last_nav_button' " .
             "onmouseover=\"changeClass('last_nav_button','last_nav_button_hover');\" " .
             "onmouseout=\"changeClass('last_nav_button','last_nav_button');\" " .
             "onclick=\"gotopage(1,%d);\" " .
             ">Next&nbsp;&gt;&gt;</div>\n",
             $numberofpages);
    } else if ($numberofpages > 1 && $postCurrentPage == $numberofpages) {
      // A 'next' button is added, to keep the esthetics. It's non-functional
      printf("          <div id='last_nav_button' class='last_nav_button' " .
             "onmouseover=\"changeClass('last_nav_button','last_nav_button_hover');\" " .
             "onmouseout=\"changeClass('last_nav_button','last_nav_button');\" " .
             ">Next&nbsp;&gt;&gt;</div>\n");
    }

    print "        </td>\n" .
          "      </tr>\n" .
          "    </table>\n";
  }

  function print_results_section($globalTableName, $sqlwherequery, $sqlorderquery) {
    $sqlselectquery = "SELECT `factoid_id`, REPLACE(`fact_key`, '\"', '\"\"') AS `fact_key`, `fact_value`, " .
      "`is_visible`, `fact`.`date_created`, `fact`.`date_last_changed`, " .
      "CASE `entry_type` WHEN 'F' THEN 'Factoid' WHEN 'T' THEN 'Trigger' ELSE 'Other' END AS `entry_type`, `channel_name`, " .
      "`user1`.`username` AS `username1`, `user2`.`username` AS `username2` " .
      "FROM `" . $globalTableName . "` AS `fact` INNER JOIN `channel` ON `fact`.`channel_id` = `channel`.`channel_id` " .
      "LEFT JOIN `bot_user` `user1` ON `fact`.`creator_user_id` = `user1`.`bot_user_id` " .
      "LEFT JOIN `bot_user` `user2` ON `fact`.`editor_user_id` = `user2`.`bot_user_id` ";

    $sqlquery = $sqlselectquery . $sqlwherequery . $sqlorderquery;
    $queryresult = mysql_query($sqlquery) or die(mysql_error());
    $num_rows = mysql_num_rows($queryresult);

    if ($num_rows == 0) {
      print "    <table border='0' cellpadding='0' cellspacing='0' width='1024' class='content_header2'>\n";
      print "      <tr>\n";
      print "        <td width='64' align='left' class='header_title2 sort'>VISIBLE</td>\n";
      print "        <td width='66' align='left' class='header_title2 sort'>TYPE</td>\n";
      print "        <td width='125' align='left' class='header_title2 sort' colspan='3'>KEY</td>\n";
      print "        <td width='769' align='left' class='header_title2 sort' colspan='2'>VALUE</td>\n";
      print "      </tr>\n";
      print "      <tr>\n";
      print "        <td colspan='7' class='header_title'>&nbsp;</td>\n";
      print "      </tr>\n";
      print "      <tr>\n";
      print "        <td colspan='7' width='1024' align='center' class='col_white'>No Results Found</td>\n";
      print "      </tr>\n";
    } else {
      print "    <table border='0' cellpadding='0' cellspacing='0' width='1024' class='content_header2'>\n";
      print "      <tr>\n";
      print "        <td width='64' align='left' class='header_title2 sort' " .
            "onclick=\"changeSortingOrder('is_visible');document.factoids.submit();\">VISIBLE</td>\n";
      print "        <td width='66' align='left' class='header_title2 sort' " .
            "onclick=\"changeSortingOrder('entry_type');document.factoids.submit();\">TYPE</td>\n";
      print "        <td width='125' align='left' class='header_title2 sort' colspan='3' " .
            "onclick=\"changeSortingOrder('fact_key');document.factoids.submit();\">KEY</td>\n";
      print "        <td width='769' align='left' class='header_title2 sort' colspan='2' " .
            "onclick=\"changeSortingOrder('fact_value');document.factoids.submit();\">VALUE</td>\n";
      print "      </tr>\n";
      print "      <tr>\n";
      print "        <td colspan='6' class='header_title'>&nbsp;</td>\n";
      print "      </tr>\n";

      $rowcount = 0;

      while ($row = mysql_fetch_array($queryresult)) {
        print "      <tr>\n";

        if ($rowcount % 2 == 0) {
          $cssclass = "grey_row";
        } else {
          $cssclass = "normal_row";
        }

        if ($row["is_visible"] == 0) {
          #printf("        <td align='center' class='col_white %s'><div id='visibility%d' class='deleted' onclick=\"alterFactoidState(%d);\"></div></td>\n",
          #       $cssclass, $row["factoid_id"], $row["factoid_id"]);
          printf("        <td align='center' class='col_white %s'><div id='visibility%d' class='deleted'></div></td>\n",
                 $cssclass, $row["factoid_id"]);
        } else {
          #printf("        <td align='center' class='col_white %s'><div id='visibility%d' class='active' onclick=\"alterFactoidState(%d);\"></div></td>\n",
          #       $cssclass, $row["factoid_id"], $row["factoid_id"]);
          printf("        <td align='center' class='col_white %s'><div id='visibility%d' class='active'></div></td>\n",
                 $cssclass, $row["factoid_id"]);
        }

        printf("        <td align='center' class='col_white %s'>%s</td>\n",
               $cssclass, $row["entry_type"]);

        $factoidkey = str_replace("\"", "&quot;", $row["fact_key"]);

        $factoidkeycleaned = str_replace("\"", "&quot;", $row["fact_key"]);
        $factoidkeycleaned = str_replace("<", "&lt;", $factoidkeycleaned);
        $factoidkeycleaned = str_replace(">", "&gt;", $factoidkeycleaned);

        printf("        <td align='left' class='col_white %s'><input type='hidden' name='key%d' id='key%d' value=\"%s\">" .
               "<input type='hidden' name='id%d' id='id%d' value=\"%s\">%s</td>\n",
          $cssclass, $row["factoid_id"], $row["factoid_id"], $factoidkey, $rowcount, $rowcount,
          $row["factoid_id"], $factoidkeycleaned);

        printf("        <td width='24' align='center' class='col_white %s'>\n" .
               "          <div id='info%d' class='info' " .
               "onclick=\"return overlib('<b>Created by</b>: %s<br><b>Created on</b>: %s<br><b>Modifed by</b>: %s" .
               "<br><b>Modified on</b>: %s<br><b>Type</b>: %s', " .
               "CAPTION, 'Factoid Properties', STICKY, FGCOLOR, '', TEXTPADDING, 8, " .
               "CAPTIONPADDING, 4, TEXTFONTCLASS, '', CAPTIONFONTCLASS, '', WRAP, BASE, 2, HAUTO, FILTER);return false;\"" .
               "></div>\n" .
               "        </td>\n",
          $cssclass, $row["factoid_id"], $row["username1"], $row["date_created"],
          $row["username2"], $row["date_last_changed"], $row["entry_type"]);

        $numofrowsrequired = ceil(strlen($row["fact_value"]) / 70);
	$factoidvalue = str_replace("<1>", "http://dev.mysql.com/doc/refman/5.5/en/", $row["fact_value"]);
        $factoidvalue = str_replace("<", "&lt;", $factoidvalue);
        $factoidvalue = str_replace(">", "&gt;", $factoidvalue);

         printf("        <td width='24' align='center' class='col_white %s'>\n" .
               "          <div id='cancel%d' class='hidden_div' " .
               "onclick=\"cancelEdit(%d);changeClass('value%d','form_element_noneditable');" .
               "changeClass('edit%d','edit');" .
               "changeClass('save%d','hidden_div');" .
               "changeClass('cancel%d','hidden_div');" .
               "\"></div>\n" .
               "        </td>\n",
               $cssclass,
               $row["factoid_id"], $row["factoid_id"], $row["factoid_id"], $row["factoid_id"],
               $row["factoid_id"], $row["factoid_id"], $row["factoid_id"]);
        #printf("        <td width='24' align='center' class='col_white %s'>\n" .
        #       "          <div id='edit%d' class='edit' " .
        #       "onclick=\"return makeFactoidValueEditable(%d,%d,75);" .
        #       "changeClass('edit%d','hidden_div');" .
        #       "changeClass('save%d','save');" .
        #       "changeClass('cancel%d','cancel');" .
        #       "\"></div>\n" .
        #       "          <div id='cancel%d' class='hidden_div' " .
        #       "onclick=\"cancelEdit(%d);changeClass('value%d','form_element_noneditable');" .
        #       "changeClass('edit%d','edit');" .
        #       "changeClass('save%d','hidden_div');" .
        #       "changeClass('cancel%d','hidden_div');" .
        #       "\"></div>\n" .
        #       "        </td>\n",
        #       $cssclass, $row["factoid_id"], $row["factoid_id"], $numofrowsrequired, $row["factoid_id"], $row["factoid_id"],
        #       $row["factoid_id"], $row["factoid_id"], $row["factoid_id"], $row["factoid_id"], $row["factoid_id"],
        #       $row["factoid_id"], $row["factoid_id"], $row["factoid_id"]);
        printf("        <td width='721' align='left' class='col_readonly_value %s'>\n " .
               "          <span id='span%d' class='form_element_noneditable'>%s</span>\n" .
               "        </td>\n",
               $cssclass, $row["factoid_id"], wordwrap($factoidvalue, 90, "\n", true), $numofrowsrequired);
        printf("        <td width='24' align='center' class='col_white %s'>\n " .
               "          <div id='save%d' class='hidden_div' " .
               "onclick=\"updateFactoidValue('%d');" .
               "changeClass('edit%d','edit');" .
               "changeClass('save%d','hidden_div');" .
               "changeClass('cancel%d','hidden_div');" .
               "\"></div>\n" .
               "        </td>\n",
               $cssclass, $row["factoid_id"], $row["factoid_id"], $row["factoid_id"], $row["factoid_id"], $row["factoid_id"]);
        print "      </tr>\n";

        $rowcount = $rowcount + 1;
      }
    }

    print "    </table>\n";
  }

  function print_footer_section() {
    print "      <div class='content_footer'></div>\n";
  }

  function build_where_section($postAction, $postStatusValue, $postTypeValue, $postSearchCriteria, $postSearchValue, $postExactMatch, $globalChannelID) {
    $sqlwherequery = "WHERE `fact`.`channel_id` = " . $globalChannelID . " ";

    if ($postAction == "search") {
      if ($postStatusValue == "active") {
        $sqlwherequery = $sqlwherequery . "AND `is_visible` = 1 ";
      } else if ($postStatusValue == "deleted") {
        $sqlwherequery = $sqlwherequery . "AND `is_visible` = 0 ";
      }

      if ($postTypeValue == "F") {
        $sqlwherequery = $sqlwherequery . "AND `entry_type` = 'F' ";
      } else if ($postTypeValue == "T") {
        $sqlwherequery = $sqlwherequery . "AND `entry_type` = 'T' ";
      } else if ($postTypeValue == "O") {
        $sqlwherequery = $sqlwherequery . "AND `entry_type` = 'O' ";
      }

      if ($postSearchValue != "" && $postSearchCriteria == "value") {
        if ($postExactMatch == "on") {
          $sqlwherequery = $sqlwherequery . "AND `fact_value` = '" .
            mysql_real_escape_string($postSearchValue) . "' ";
        } else {
          $sqlwherequery = $sqlwherequery . "AND `fact_value` LIKE '%" .
            mysql_real_escape_string($postSearchValue) . "%' ";
        }
      } else if ($postSearchValue != "" && $postSearchCriteria == "key") {
        if ($postExactMatch == "on") {
          $sqlwherequery = $sqlwherequery . "AND `fact_key` = '" .
            mysql_real_escape_string($postSearchValue) . "' ";
        } else {
          $sqlwherequery = $sqlwherequery . "AND `fact_key` LIKE '%" .
            mysql_real_escape_string($postSearchValue) . "%' ";
        }
      } else if ($postSearchValue != "" && $postSearchCriteria == "both") {
        if ($postExactMatch == "on") {
          $sqlwherequery = $sqlwherequery . "AND (`fact_key` = '" .
            mysql_real_escape_string($postSearchValue) . "' OR `fact_value` = '" .
            mysql_real_escape_string($postSearchValue) . "') ";
        } else {
          $sqlwherequery = $sqlwherequery . "AND (`fact_key` LIKE '%" .
            mysql_real_escape_string($postSearchValue) . "%' OR `fact_value` LIKE '%" .
            mysql_real_escape_string($postSearchValue) . "%') ";
        }
      }
    }

    return $sqlwherequery;
  }

  function build_order_section ($postOrderByColumn, $postOrderByOrder, $postCurrentPage, $startindex) {
    $sqlorderquery = "";
    $sqllimit = "";

    // Dynamic ordering
    if ($postOrderByColumn != "") {
      if ($postOrderByOrder != "") {
        $sqlorderquery = "ORDER BY `" . $postOrderByColumn . "` " .
          $postOrderByOrder . " ";
      } else {
        $sqlorderquery = "ORDER BY `" . $postOrderByColumn . "` ASC ";
      }
    } else {
      $sqlorderquery = "ORDER BY `fact_key` ASC ";
    }

    if ($postCurrentPage != "") {
      $sqllimit = "LIMIT " . $startindex . ",50";
    } else {
      $sqllimit = "LIMIT 0,50";
    }

    return $sqlorderquery . $sqllimit;
  }

  function build_totals_query($globalTableName) {
    $sqlselectquery2 = "SELECT COUNT(`factoid_id`) AS `factoid_id` FROM `" . $globalTableName . "` `fact` ";
  }

  function get_channel_name($channelID) {
    $channel_name = "";
    $sql = "SELECT `channel_name` FROM `channel` WHERE `channel_id` = " . $channelID . " ";
    $queryresult = mysql_query($sql) or die(mysql_error());

    while ($row = mysql_fetch_array($queryresult)) {
      $channel_name = $row["channel_name"];
    }

    return $channel_name;
  }
?>
